package com.gl.saasservice.department.service;

import com.gl.common.vo.ApiData;
import com.gl.framework.web.response.Result;
import com.gl.saasservice.department.vo.DepartmentPersonnelServiceVo;
import com.gl.saasservice.entity.AppUser;
import com.gl.saasservice.entity.User;
import com.gl.saasservice.house.service.HouseService;
import com.gl.saasservice.house.vo.HouseVO;
import com.gl.saasservice.repository.AppUserRepository;
import com.gl.saasservice.repository.ServerUserRepository;
import com.gl.saasservice.repository.UserRepository;
import com.gl.saasservice.repository.UserRoleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class DepartmentPersonnelService {

    private static final Logger log = LoggerFactory.getLogger(DepartmentPersonnelService.class);
    @Autowired
    private ServerUserRepository serverUserRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    /**
     * 查询机构用户列表
     */
    public Result list(String token, Integer pageNumber, Integer pageSize, String departmentname, String companyName, String userName,String phone, String position) {
        try {
            ApiData<DepartmentPersonnelServiceVo> apiData = new ApiData<>();
            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();

            where.append(" a.userType != 1  and a.status = 1");
            if(departmentname != null){
                where.append(" and a.departmentname LIKE ?");
                args.add("%"+departmentname+"%");
            }
            if(companyName != null){
                where.append(" and a.companyName LIKE ?");
                args.add("%"+companyName+"%");
            }
            if(userName != null){
                where.append(" and a.userName LIKE ?");
                args.add("%"+userName+"%");
            }
            if(phone != null){
                where.append(" and a.phone LIKE ?");
                args.add("%"+phone+"%");
            }
            if(position != null){
                where.append(" and a.position LIKE ?");
                args.add("%"+position+"%");
            }
            String count ="SELECT\n" +
                    "\tcount(1)\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "SELECT\n" +
                    "\td.NAME AS departmentname,\n" +
                    "\tIFNULL( dd.NAME, d.NAME ) AS companyName,\n" +
                    "\tu.id AS userId,\n" +
                    "\tu.NAME AS userName,\n" +
                    "\tu.type AS userType,\n" +
                    "\tu.mobile AS phone,\n" +
                    "\tu.position,\n" +
                    "\tu.create_time AS createTime,\n" +
                    "\tu.status \n" +
                    "FROM\n" +
                    "\t`saas_department` d\n" +
                    "\tINNER JOIN saas_user_department_ref udr ON d.id = udr.dep_id\n" +
                    "\tINNER JOIN saas_user u ON udr.user_id = u.id\n" +
                    "\tLEFT JOIN saas_department dd ON dd.id = d.parent_id \n" +
                    "\t) a \n" +
                    "WHERE";

            String SQL="SELECT\n" +
                    "\t* \n" +
                    "FROM\n" +
                    "\t(\n" +
                    "SELECT\n" +
                    "\td.NAME AS departmentname,\n" +
                    "\tIFNULL( dd.NAME, d.NAME ) AS companyName,\n" +
                    "\tu.id AS userId,\n" +
                    "\tu.NAME AS userName,\n" +
                    "\tu.type AS userType,\n" +
                    "\tu.mobile AS phone,\n" +
                    "\tu.position,\n" +
                    "\tu.create_time AS createTime,\n" +
                    "\tu.status \n" +
                    "FROM\n" +
                    "\t`saas_department` d\n" +
                    "\tINNER JOIN saas_user_department_ref udr ON d.id = udr.dep_id\n" +
                    "\tINNER JOIN saas_user u ON udr.user_id = u.id\n" +
                    "\tLEFT JOIN saas_department dd ON dd.id = d.parent_id \n" +
                    "\t) a \n" +
                    "WHERE";
            Long total = jdbcTemplate.queryForObject(count + where, Long.class, args.toArray());
            if (total == 0) {
                return Result.success(apiData);
            }
            // 查询分页数据
            String offsets = " limit ? offset ?";
            where.append(" ORDER BY ").append(" a.createTime desc ").append(" \n").append(offsets);
            args.add(pageSize);
            args.add((pageNumber - 1) * pageSize);
            List<DepartmentPersonnelServiceVo> data = jdbcTemplate.query(SQL + where,new BeanPropertyRowMapper<>(DepartmentPersonnelServiceVo.class), args.toArray());
            apiData.setTotal(total);
            apiData.setData(data);
            return Result.success(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
}

    /**
     * 批量删除机构用户
     */
    public Result delete(String token, String[] userIds) {
        try {
            if (userIds == null) {
                return Result.fail();
            }
            for (String userId : userIds) {
                Optional<User> byId = serverUserRepository.findById(userId);
                User user = byId.get();
                Short status = 2;
                user.setLeaveDate(new Date());
                user.setStatus(status);
                serverUserRepository.save(user);
                userRoleRepository.deleteByUserId(userId);
                AppUser appUser = appUserRepository.findByEnterpriseUserId(userId);
                if (appUser != null) {
                    String appUserId = appUser.getId();
                    appUserRepository.deleteById(appUserId);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail();
        }
        return Result.success("删除成功");
    }
}
